<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserCompany;
use support\Request;
use support\Response;
use plugin\admin\app\model\DesignerApplication;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 设计师申请 
 */
class DesignerApplicationController extends Crud
{
    
    /**
     * @var DesignerApplication
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new DesignerApplication;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('designer-application/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('designer-application/insert');
    }

    protected function doUpdate($id, $data)
    {
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }

        if ($data['is_approved'] == DesignerApplication::STATUS_APPROVED) {
            User::where('id', $model['user_id'])->update(['is_creator' => 1]);
            UserCompany::insert([
                'user_id' => $model['user_id'],
                'company_logo' => $model['logo'],
                'company_name' => $model['company_name'],
            ]);
        }

        foreach ($data as $key => $val) {
            $model->{$key} = $val;
        }
        $model->save();
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('designer-application/update');
    }

    protected function formatNormal($items, $total): Response
    {
        foreach ($items as $key=>$item) {

            $items[$key]['is_approved_text'] = DesignerApplication::STATUS_TEXT[$item['is_approved']];
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }
}
